#include "PSPInput.h"

#include <pspctrl.h>

namespace GenBen {

PSPInput::PSPInput()
{
	current_state = last_state = 0;
	
	sceCtrlSetSamplingCycle(0);
	sceCtrlSetSamplingMode(PSP_CTRL_MODE_ANALOG);
}

PSPInput::~PSPInput()
{
}

bool PSPInput::isKeyPressed(Key key)
{
	uint mask = keyToMask(key);
	return (current_state & mask) != 0;
}

bool PSPInput::isKeyUp(Key key)
{
	uint mask = keyToMask(key);
	return !((current_state & mask) != 0) && ((last_state & mask) != 0);
}

bool PSPInput::isKeyDown(Key key)
{
	uint mask = keyToMask(key);
	return ((current_state & mask) != 0) && !((last_state & mask) != 0);
}

void PSPInput::update()
{
	SceCtrlData controls;
	sceCtrlPeekBufferPositive(&controls, 1);
	last_state = current_state;
	current_state = controls.Buttons;
}

uint PSPInput::keyToMask(Key key)
{
	switch(key)
	{
		case PSPKEY_UP:
			return PSP_CTRL_UP;
		case PSPKEY_DOWN:
			return PSP_CTRL_DOWN;
		case PSPKEY_LEFT:
			return PSP_CTRL_LEFT;
		case PSPKEY_RIGHT:
			return PSP_CTRL_RIGHT;
			
		case PSPKEY_CROSS:
			return PSP_CTRL_CROSS;
		case PSPKEY_CIRCLE:
			return PSP_CTRL_CIRCLE;
		case PSPKEY_SQUARE:
			return PSP_CTRL_SQUARE;
		case PSPKEY_TRIANGLE:
			return PSP_CTRL_TRIANGLE;
			
		case PSPKEY_L:
			return PSP_CTRL_LTRIGGER;
		case PSPKEY_R:
			return PSP_CTRL_RTRIGGER;
		case PSPKEY_SELECT:
			return PSP_CTRL_SELECT;
		case PSPKEY_START:
			return PSP_CTRL_START;
		default:
			return 0; 
	}
}
	
} // namespace
